<?php
class Silk_Mapi_CartController extends Silk_Mapi_Controller_Action{
    public function indexAction() {
        $data = array();
        $quote = $this->_getCart()->getQuote();
        $data['subtotal'] = $quote->getSubtotal();
        $data['grand_total'] = $quote->getGrandTotal();
        try
        {
            $data['items'] = $this->getAllItemData();
        }
        catch(Exception $e)
        {
            $this->renderError($e->getMessage());
            return;
        }
        $this->render($data);
    }
    

    public function _getCart()
    {
    	return Mage::getSingleton('checkout/cart');
    }

    public function _getQuote()
    {
        return $this->_getCart()->getQuote();
    }

    public function _getCheckoutSession()
    {
    	return Mage::getSingleton('checkout/session');
    }

    public function _getCustomerSession()
    {
    	return Mage::getSingleton('customer/session');
    }

    public function getCartData($checkQty = false)
    {
    	$data = array();
        $quote = $this->_getCart()->getQuote();
        $quote->collectTotals()->save();
        $data['subtotal'] = $quote->getSubtotal();
        $points = $this->getPointsForCheckout();
        if($points)
        {
            $data['grand_total'] = $quote->getSubtotal()-($points/50);
            if($data['grand_total']<=0) $data['grand_total'] = 0;
        }
        else
        {
            $data['grand_total'] = $quote->getGrandTotal();
        }
        $data['items'] = $this->getAllItemData($checkQty);
        return $data;
    }

    /**
     * Get one page checkout model
     *
     * @return Mage_Checkout_Model_Type_Onepage
     */
    public function getOnepage()
    {
        return Mage::getSingleton('checkout/type_onepage');
    }


    public function getAllItemData($checkQty = false)
    {
    	$_imageHelper = Mage::helper('catalog/image');
    	$cart = $this->_getCart();
    	$quote = $cart->getQuote();
    	$items = $quote->getAllItems();

    	$itemsData = array();

    	foreach($items as $item)
    	{
            $product = $item->getProduct();
            $product->load($item->getProductId());
            $stockItem = $product->getStockItem();
            if($checkQty)
            {

                
                $minQty = $stockItem->getData('min_sale_qty');
                $minQty = intval($minQty);
                if($minQty>$item->getQty() && $checkQty)
                {
                    throw new Exception("{$product->getName()}最少订购不能少于{$minQty}！");
                }
            }
            if($item->getQty()>$stockItem->getQty() && $checkQty)
            {
                throw new Exception("{$product->getName()}库存不足！");
            }
    		$itemsData[] = array(
    			'item_id'=>$item->getId(),
    			'product_id'=>$item->getProductId(),
    			'name'=>$item->getName(),
    			'price'=>$item->getPrice(),
    			'image'=>$_imageHelper->init($item->getProduct(), 'small_image')->resize(135)."",
    			'qty'=>$item->getQty(),
    			'stock_qty'=>intval($stockItem->getQty()),
                'subtotal'=>$item->getRowTotal()

    		);
    	}
    	return $itemsData;
    }

    /**
     * get reward points spending block helper
     * 
     * @return Magestore_RewardPoints_Helper_Block_Spend
     */
    public function getSpendHelper()
    {
        return Mage::helper('rewardpoints/block_spend');
    }
    
    /**
     * get reward points helper
     * 
     * @return Magestore_RewardPoints_Helper_Point
     */
    public function getPointHelper()
    {
        return Mage::helper('rewardpoints/point');
    }

    public function getSpendRule()
    {
        $block = new Magestore_RewardPoints_Block_Checkout_Onepage_Payment_Rewrite_Methods();
        $rules = $block->getSliderRules();
        return current($rules);
    }

    public function checkAddMaxPoint($_product,$qty)
    {
        $items = $this->_getQuote()->getAllItems();
        $totalPrice = 0;
        foreach($items as $item)
        {
            $prod = $item->getProduct();
            $prod->load($item->getProductId());
            if($prod->getUsePoint())
            {
                $totalPrice += ($prod->getFinalPrice()*$item->getQty());
            }
        }
        $totalPrice += ($_product->getFinalPrice()*$qty);
        $_customer = $this->_getCustomerSession()->getCustomer();
        $spendHelper = $this->getSpendHelper();
        $rule = $this->getSpendRule();

        $points = $spendHelper->getCustomerPoint();
        $spendHelper = $this->getSpendHelper();
        $rule = $this->getSpendRule();
        $toRate = $rule->getPointsSpended();
        $maxSpend = intval($points/$toRate);
        if($maxSpend>$totalPrice)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function getPointsForCheckout()
    {
        $items = $this->_getQuote()->getAllItems();
        $totalPrice = 0;
        foreach($items as $item)
        {
            $prod = $item->getProduct();
            $prod->load($item->getProductId());
            if($prod->getUsePoint())
            {
                $totalPrice += ($prod->getFinalPrice()*$item->getQty());
            }
        }
        
       // return ceil($totalPrice*50);
       //add by wanglin start 问题：pc端购买积分商品生成的订单一半积分；一半正常价格。
       return 0;
       //add by wanglin end 问题：pc端购买积分商品生成的订单一半积分；一半正常价格。
    }

    public function addAction()
    {
    	$id = $this->getRequest()->getParam('id');
    	$sku = $this->getRequest()->getParam('sku');
    	$qty = $this->getRequest()->getParam('qty', 1);

    	if(!$id && $sku)
    	{
    		$id = Mage::getModel('catalog/product')->getIdBySku($sku);
    	}

    	$product = $this->_initProduct($id);

        if($product && $product->getUsePoint())
        {
            if(!$this->checkAddMaxPoint($product, $qty))
            {
                $this->renderError('积分不足！');
                return;
            }
        }
        
    	/**
         * Check product availability
         */
        if (!$product) {
            $this->renderError('商品不存在！');
            return;
        }

        $cart = $this->_getCart();
        $params = array('product'=>$product->getId(), 'qty'=>$qty);

        try
        {
        	$cart->addProduct($product, $params);
        	$cart->save();
        	$this->render($this->getCartData());
        }
        catch(Mage_Core_Exception $e)
        {
            $this->renderError($e->getMessage());

        }
        catch(Exception $e)
        {
            $this->renderError("库存不足！".$e->getMessage());
        }
    }

    public function _initProduct($productId)
    {
        if ($productId) {
            $product = Mage::getModel('catalog/product')
                ->setStoreId(Mage::app()->getStore()->getId())
                ->load($productId);
            if ($product->getId()) {
                return $product;
            }
        }
        return false;
    }

    public function updatePostAction()
    {
    	$items = $this->getRequest()->getParam('items');
    	$quote = $this->_getCart()->getQuote();
    	try
    	{
    		$cartData = array();
    		foreach($items as $id=>$qty)
    		{
    			$cartData[$id] = array('qty'=>$qty);
    		}

    		$this->_getCart()->updateItems($cartData)->save();
    		$this->_getCheckoutSession()->setCartWasUpdated(true);
    		$this->render($this->getCartData());
    	}
    	catch(Exception $e)
    	{
    		$this->renderError($e->getMessage());
    	}
    }

    public function deleteAction()
    {
    	$id = (int) $this->getRequest()->getParam('id');
        if ($id) {
            try {
                $this->_getCart()->removeItem($id)->save();
                $this->render(array());
                return;
            } catch (Exception $e) {
                $this->renderError($e->getMessage());
                return;
            }
        }
        $this->renderError("商品不存在！");
    }

    public function checkoutAction()
    {	
    	if(!$this->_getCart()->getItemsCount())
    	{
    		$this->renderError('购物车为空！');
    		return;
    	}

    	$_session = $this->_getCheckoutSession();
    	$_customer = $this->_getCustomerSession()->getCustomer();
    	$addresss = $_customer->getAddressesCollection();
    	$address = null;

    	if(count($addresss))
    	{
    		$address = $addresss->getFirstItem();
    	}
    	else
    	{
    		$this->renderError('请先设置收货地址！');
    		return;
    	}

        $spendHelper = $this->getSpendHelper();
        $points = $spendHelper->getCustomerPoint();
        if($this->getPointsForCheckout()>$points)
        {
            $this->renderError("你的积分不足！");
            return;
        }

        ///************************
        $onepage = $this->getOnepage();
        $quoteId = $onepage->getQuote()->getId();

        //save billing address
        $customerAddressId = $address->getId();
        $onepage->saveBilling(array('use_for_shipping'=>1), $customerAddressId);

        $_session->setData('use_point', true);
        $_session->getQuote()->collectTotals()->save();


        $rule = $this->getSpendRule();
        $_session->setRewardSalesRules(array(
            'rule_id' => $rule->getId(),
            'use_point' => $this->getPointsForCheckout(),
        ));
        $_session->getQuote()->collectTotals()->save();

        //save shipping method
        $data = 'freeshipping_freeshipping';
        $onepage->saveShippingMethod($data);

        //save payment method
        $data = array('method'=>'cashondelivery');
        $onepage->savePayment($data);
        //$this->render(array('quote_id'=>$session->getQuote()->getId()));
        //$_session->getQuote()->save();
        
        $quote = $_session->getQuote();
        $quote->getTotals();
        $quote->setIsMultiShipping(false);
        $quote->setIsMultiWarehouse(null);
        $quote->save();
        //$rs = array(
        //    'grand_total'=>$quote->getGrandTotal(),
        //    'subtotal'=>$quote->getSubtotal()
        //    );
        
        //$this->render($rs);
        //return;
        ///************************
        //$_session->clear();
        //$_session = null;

        try
        {
    	   $data = $this->getCartData(true);
        }
        catch(Exception $e)
        {
            $this->renderError($e->getMessage());
            return;
        }

        $grandPrice = number_format(Mage::getModel('checkout/cart')->getQuote()->getGrandTotal(),2);
        $subPrice   = number_format(Mage::getModel('checkout/cart')->getQuote()->getSubtotal(),2);
    	$checkoutData = array();
        $checkoutData['price'] = array(
                'grandprice' => $grandPrice,
                'subPrice' => $subPrice,
            );
    	$checkoutData['payment_method'] = "货到付款";
    	$checkoutData['shipping_method'] = "免费配送";
    	$checkoutData['shipping_address'] = array(
    			'name'=>$address->getFirstname(),
    			'mobile'=>$address->getTelephone(),
    			'address'=>$address->oneLine(),
    		);

    	$data+=$checkoutData;
    	$this->render($data);
    }

    public function placeAction()
    {
    	$_session = $this->_getCheckoutSession();
    	$_customer = $this->_getCustomerSession()->getCustomer();
    	$addresss = $_customer->getAddressesCollection();
    	$address = null;
    	
    	if(!$this->_getCart()->getItemsCount())
    	{
    		$this->renderError('购物车为空！');
    		return;
    	}

    	if(count($addresss))
    	{
    		$address = $addresss->getFirstItem();
    	}
    	else
    	{
    		$this->renderError('请先设置收货地址！');
    		return;
    	}

        $spendHelper = $this->getSpendHelper();
        $points = $spendHelper->getCustomerPoint();
        if($this->getPointsForCheckout()>$points)
        {
            $this->renderError("你的积分不足！");
            return;
        }

    	$onepage = $this->getOnepage();

    	try
    	{
    		$quoteId = $onepage->getQuote()->getId();

    		//save billing address
	    	$customerAddressId = $address->getId();
	    	$onepage->saveBilling(array('use_for_shipping'=>1), $customerAddressId);

            $_session->setData('use_point', true);
            $_session->getQuote()->collectTotals()->save();


            $rule = $this->getSpendRule();
            $_session->setRewardSalesRules(array(
                'rule_id' => $rule->getId(),
                'use_point' => $this->getPointsForCheckout(),
            ));
            $_session->getQuote()->collectTotals()->save();

            //save shipping method
            $data = 'freeshipping_freeshipping';
            $onepage->saveShippingMethod($data);

	    	//save payment method
	    	$data = array('method'=>'cashondelivery');
	    	$onepage->savePayment($data);
            //$this->render(array('quote_id'=>$session->getQuote()->getId()));
            $_session->getQuote()->save();

            $quote = $_session->getQuote();
            $rs = array(
                'grand_total'=>$quote->getGrandTotal(),
                'subtotal'=>$quote->getSubtotal()
                );
            $this->render($rs);
            //return;
	    	//save order
	    	$onepage->saveOrder();

	    	$collection = Mage::getModel('sales/order')->getCollection()
	    		->addFieldToFilter('quote_id', array('eq'=>$quoteId));
	    	if(count($collection))
	    	{
	    		$order = $collection->getFirstItem();
	    		$orderId = $order->getIncrementId();
	    		if($orderId)
	    		{
	    			$this->_getCart()->truncate()->save();
        			$this->_getCheckoutSession()->setCartWasUpdated(true);
        			$this->render(array('order_id'=>$orderId),"你的订单已经生成，订单号：{$orderId}");
	    			return;
	    		}
	    		else
	    		{
	    			$this->renderError("订单未找到！");
    				return;
	    		}
	    		
	    	}
    	}catch(Exception $e){
    		$this->renderError("订单保存失败！".$e->getMessage());
    		return;
    	}
    }

    public function emptyAction()
    {
    	try
    	{
    		$this->_getCart()->truncate()->save();
        	$this->_getCheckoutSession()->setCartWasUpdated(true);
        	$this->render(array());
    	}
    	catch(Exception $e)
    	{
    		$this->renderError("操作失败！");
    	}
    }

    public function reorderAction()
    {
        $id = $this->getRequest()->getParam('id');
        $order = Mage::getModel('sales/order')->load($id);
        if($order && $order->getId())
        {
            $items = $order->getItemsCollection();
            $cart = Mage::getSingleton('checkout/cart');
            $error = '';
            foreach ($items as $item) {
                try {
                    $cart->addOrderItem($item);
                } catch (Mage_Core_Exception $e){
                    $error .= $e->getMessage().'\n';
                } catch (Exception $e) {
                    $error .= $e->getMessage().'\n';
                }
            }
            $cart->save();
            if($error)
            {
                $this->renderError($error);
            }
            else
            {
                $this->render(array(), '商品已加入购物车！');
            }
            
        }
        else
        {
            $this->renderError("订单不存在！");
        }
    }
}